﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace Frame
{
    class DataHelper
    {
        static string connStr = @"server=LAPTOP-O0HV5PVJ;database=Test;Integrated Security=true";
        public static string ConnStr
        {
            get { return connStr; }
        }
        #region 非查询性操作
        public static int sqlExecuteNonQuery(string sql)//插入 删除 增加操作
        {
            if (ConnStr == null)
                return 0;
            SqlConnection sqlConnection = new SqlConnection(ConnStr);
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlConnection.Open();
            int result = sqlCommand.ExecuteNonQuery();
            sqlConnection.Close();
            return result;
        }
        #endregion
        #region 单变量查询
        public static int sqlExecuteScalar(string sql)
        {
            if (ConnStr == null)
                return 0;
            SqlConnection sqlConnection = new SqlConnection(ConnStr);
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlConnection.Open();
            object o = sqlCommand.ExecuteScalar();
            sqlConnection.Close();
            return (int)o;
        }
        #endregion
        #region dataset传入sql语句和表名
        public static SqlDataAdapter SqlDataAdapter(string sql, string name)
        {
            if (ConnStr == null)
                return null;
            SqlConnection sqlConnection = new SqlConnection(ConnStr);
            SqlDataAdapter da = new SqlDataAdapter(sql, sqlConnection);
            DataSet ds = new DataSet();
            da.Fill(ds, name);
            return da;
        }
        #endregion
        #region datareader
        public static SqlDataReader ExecuteReader(string sql)
        {
            if (ConnStr == null)
                return null;
            SqlConnection sqlConnection = new SqlConnection(ConnStr);
            SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
            sqlConnection.Open();
            SqlDataReader reader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
            return reader;
        }

        #endregion
    }
}
